const db = require('../tool/db.js')
const bcrypt = require('bcrypt');
const common = require('../model/common.js')
const jwt = require('jsonwebtoken')
//用户注册
async function register(data) {
    if (!data.userName || data.userName.length < 2 || data.userName.length > 10) {
        return {
            code: 0,
            msg: '昵称的长度应在2-10个字符之间',
            data: ''
        }
    }

    let regx = /^1[356789]\d{9}$/
    if (!regx.test(data.mobile)) {
        return {
            code: 0,
            msg: '手机号格式有误',
            data: ''
        }
    }

    if (!data.password || data.password.length < 6 || data.password.length > 16) {
        return {
            code: 0,
            msg: '密码的长度应在6-16个字符之间',
            data: ''
        }
    }

    let mobileExist = await common.mobileExist(data.mobile)
    if (mobileExist.length) {
        return {
            code: 0,
            msg: '手机号已存在',
            data: ''
        }
    }

    let userNameExist = await common.userNameExist(data.userName)
    if (userNameExist.length) {
        return {
            code: 0,
            msg: '用户名重复',
            data: ''
        }
    }

    data.password = await bcrypt.hash(data.password, 10);
    let [res] = await db.query('insert into user (username,password,mobile) values(?,?,?)', [data.userName, data.password, data.mobile])
    if (!res.insertId) {
        return {
            code: 0,
            msg: '注册失败,请重试',
            data: ''
        }
    }
    return {
        code: 1,
        msg: '注册成功',
        data: ''
    }
}

//用户登录
async function login(info) {
    let token = jwt.sign({
        id: info.id,
        username: info.username,
        mobile: info.mobile,
        exp: Math.floor(Date.now() / 1000) + 86400 // 24小时后过去
    }, 'dgfshjdsjhgdhbas')

    return token
}

//修改用户名
async function modUserName(data){
    let [res] = await db.query('update user set username = ? where id = ?',[data.newUserName,data.id])
    if(res.changedRows){
        return {code:1,msg:'修改成功',data:''}
    }
}

//修改密码
async function modPassword(data){
    data.newPassword = await bcrypt.hash(data.newPassword, 10);
    let [res] = await db.query('update user set password = ? where id = ?',[data.newPassword,data.id])
    if(res.changedRows){
        return {code:1,msg:'修改成功',data:''}
    }
    
}

async function paypwd(data){
    data.paypassword = await bcrypt.hash(data.paypassword, 10);

    let [paypasswordExist] = await db.query('select paypassword from user where id = '+ data.uid)
    if(paypasswordExist.length){
        return {code:0,msg:'非法操作',data:''}
    }
    let [res] = await db.query('update user set paypassword = ? where id = ?',[data.paypassword,data.uid])

    if(res.affectedRows){
        return {code:1,msg:'设置成功',data:''}
    }
}

module.exports = {
    register,login,modUserName,modPassword,paypwd
}